package com.csglxt.view.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.csglxt.base.BaseAction;
import com.csglxt.domain.Market;
import com.csglxt.domain.OnshelvesInfo;
import com.csglxt.domain.Order;
import com.csglxt.domain.OrderItem;
import com.csglxt.domain.Storage;
import com.csglxt.domain.Supplier;
import com.csglxt.utils.DateUtil;
import com.csglxt.utils.QueryHelper;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @ClassName: StorageAction
 * @Description: TODO(库存管理控制器 （上架，下架，进货，退货操作，四种类型单据生成）)
 * @author Itchbeilef
 * @date 2015-5-28 下午9:00:58
 * 
 */
@Controller
@Scope("prototype")
@SuppressWarnings("serial")
public class StorageAction extends BaseAction<Storage> {
    // 解决session订单生成
    private String storageIdStr; // 库存ID
    private String goodsIdStr; // 商品ID
    private String marketId; // 超市ID
    private String supplierId; // 供应商ID
    // 解决搜索、页面判断、session订单生成
    private String dealType; // 单据类型
    // 解决搜索
    private String GoodsName; // 商品名
    private String goodsCateId; // 商品分类ID
    // 解决验证 更新订单商品数
    private String goodsnum; // 商品数量

    /**
     * 
     * @Title: list
     * @Description: TODO(库存列表显示)
     * @param
     * @return
     * @throws
     */
    public String list() {
        listStorage();
        ActionContext.getContext().put("goodsCateList",
                goodsCateService.findAll());
        return "list";
    }

    /**
     * 
     * @Title: caozuo
     * @Description: TODO(库存操作界面显示(上架、下架、进货、退货操作)根据dealType的值不同视图显示不同)
     * @param
     * @return
     * @throws
     */
    public String caozuo() {
        if (dealType != null && !dealType.isEmpty() && dealType.equals("1")
                || dealType.equals("2")) {
            ActionContext.getContext().put("marketList",
                    marketService.findAll());
        } else {
            ActionContext.getContext().put("supplierList",
                    supplierService.findAll());
        }
        if (dealType != null && !dealType.isEmpty() && dealType.equals("2")) {
            listOnshelves();
        } else {
            listStorage();
        }
        ActionContext.getContext().put("goodsCateList",
                goodsCateService.findAll());
        return "caozuo";
    }

    /**
     * 
     * @Title: listOnshelves
     * @Description: TODO(超市上架商品列表分页查询 存进栈顶)
     * @param
     * @return
     * @throws
     */
    private void listOnshelves() {
        QueryHelper qureyHelper = new QueryHelper(OnshelvesInfo.class, "o");
        if (GoodsName != null && !GoodsName.isEmpty()) {
            qureyHelper.addCondition("o.goods.name like ?", "%" + GoodsName
                    + "%");//
        }
        if (goodsCateId != null && !goodsCateId.isEmpty()
                && !goodsCateId.equals("0")) {
            qureyHelper.addCondition(" o.goods.goodsCate.id = ? ", goodsCateId);
        }
        if (marketId != null && !marketId.isEmpty()) {
            qureyHelper
                    .addCondition("o.market.id like ?", "%" + marketId + "%");//
        }
        qureyHelper.preparePageBean(goodsService, pageNum, pageSize);
    }

    /**
     * 
     * @Title: listStorage
     * @Description: TODO(库存商品列表分页查询 存进栈顶)
     * @param
     * @return
     * @throws
     */
    private void listStorage() {
        QueryHelper qureyHelper = new QueryHelper(Storage.class, "s");
        if (GoodsName != null && !GoodsName.isEmpty()) {
            qureyHelper.addCondition("s.goods.name like ?", "%" + GoodsName
                    + "%");//
        }
        if (goodsCateId != null && !goodsCateId.isEmpty()
                && !goodsCateId.equals("0")) {
            qureyHelper.addCondition(" s.goods.goodsCate.id = ? ", goodsCateId);
        }
        qureyHelper.preparePageBean(goodsService, pageNum, pageSize);
    }

    /**
     * 
     * @Title: ajaxGetOrderPara
     * @Description: TODO(异步 添加到选中商品 到(上架车/下架车 /进货车/退货车) 并保存到Sesssion)
     * @param
     * @return
     * @throws
     */
    public void ajaxGetOrderPara() {
        if (dealType.trim().isEmpty()) {
            return;
        }
        Order order = getorderSession(dealType);
        if (order == null) {
            Supplier supplier = null;
            if (supplierId != null) {
                supplier = supplierService.getById(supplierId);
            }
            Market market = null;
            if (marketId != null) {
                market = marketService.getById(marketId);
            }
            order = new Order();
            Set<OrderItem> orderItemList = new HashSet<OrderItem>();
            if (dealType.equals("3") || dealType.equals("4")) {
                order.setSupplier(supplier);
            } else {
                order.setMarket(market);
            }
            order.setOrderItems(orderItemList);
            order.setDealType(new BigDecimal(dealType));
            order.setDate(DateUtil.getCursqlDate());
        }
        if (!goodsIdStr.trim().isEmpty()) {
            String[] goodsIdArray = goodsIdStr.split(",");
            bygoodsIdArraytoOrderItem(goodsIdArray, order.getOrderItems());
        }
        putSession(order);
    }

    /**
     * 
     * @Title: putSession
     * @Description: TODO(private 根据不同操作类型添加单据到不同的Session)
     * @param order
     *            单据
     * @return
     * @throws
     */
    private void putSession(Order order) {
        int i = order.getDealType().intValue();
        if (i == 1) {
            getSession().put("order1", order);
        }
        if (i == 2) {
            getSession().put("order2", order);
        }
        if (i == 3) {
            getSession().put("order3", order);
        }
        if (i == 4) {
            getSession().put("order4", order);
        }
    }

    /**
     * 
     * @Title: getorderSession
     * @Description: TODO(private 根据不同操作类型从Session取出不同的单据)
     * @param dealtype
     *            ： 操作类型
     * @return
     * @throws
     */
    private Order getorderSession(String dealtype) {
        if (dealtype.equals("1")) {
            return (Order) getSession().get("order1");
        }
        if (dealtype.equals("2")) {
            return (Order) getSession().get("order2");
        }
        if (dealtype.equals("3")) {
            return (Order) getSession().get("order3");
        }
        if (dealtype.equals("4")) {
            return (Order) getSession().get("order4");
        }
        return null;
    }

    /**
     * 
     * @Title: bygoodsIdArraytoOrderItem
     * @Description: TODO(private 根据商品编号把商品捡到 单据明细车 里)
     * @param goodsIdArray
     *            :商品id数组 Items：单据明细集合
     * @return
     * @throws
     */
    private void bygoodsIdArraytoOrderItem(String[] goodsIdArray,
            Set<OrderItem> Items) {
        boolean b = false;
        for (int i = 0; i < goodsIdArray.length; i++) {
            for (OrderItem orderItem : Items) {
                if (goodsIdArray[i].equals(orderItem.getGoods().getId())) {
                    b = true;
                    break;
                }
            }
            if (b) {
                continue;
            }
            OrderItem item = new OrderItem();
            item.setGoods(goodsService.getById(goodsIdArray[i]));
            item.setNumber(new BigDecimal(0));
            Items.add(item);
        }
    }

    /**
     * 
     * @Title: toOrder
     * @Description: TODO(上架车、下架车、进货车、退货车 页面 根据不同操作类型显示不同的单据明细车)
     * @param
     * @return
     * @throws
     */
    public String toOrder() throws IOException {
        Object obj = null;
        if (dealType.equals("1")) {
            obj = getSession().get("order1");
        } else if (dealType.equals("2")) {
            obj = getSession().get("order2");
        } else if (dealType.equals("3")) {
            obj = getSession().get("order3");

        } else if (dealType.equals("4")) {
            obj = getSession().get("order4");
        } else {
            return null;
        }
        if (obj == null) {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<h1>空车</h1>");
            return null;
        }
        getValueStack().push(obj);
        return "saveUI";
    }

    /**
     * 
     * @Title: updateGoodsnum
     * @Description: TODO(异步 更新单据明细车 里明细的数量)
     * @param
     * @return
     * @throws
     */
    public void updateGoodsnum() throws IOException {
        Order order = getorderSession(dealType);
        for (OrderItem item : order.getOrderItems()) {
            if (item.getGoods().getId().equals(goodsIdStr.trim())) {
                item.setNumber(new BigDecimal(goodsnum.trim()));
                break;
            }
        }
    }

    /**
     * 
     * @Title: goodsnumValidation
     * @Description: TODO(异步 验证 单据明细车 里的数量是否输入超范围 返回验证结果信息)
     * @param
     * @return
     * @throws
     */
    public void goodsnumValidation() throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        String msg = null;
        if (dealType.equals("1") || dealType.equals("4")) {
            int sjk = storageService.queryGoodsNumbygoodsid(goodsIdStr);
            int jm = new Integer(goodsnum.trim()).intValue();
            if (jm > sjk) {
                msg = "库存不足";
            }
        } else if (dealType.equals("2") && !marketId.isEmpty()) {
            int sjk = onshelvesInfoService.queryGoodsNumbygoodsid(goodsIdStr,
                    marketId);
            int jm = new Integer(goodsnum.trim()).intValue();
            if (jm > sjk) {
                msg = "超市架商品不足";
            }
        }
        if (msg == null) {
            response.getWriter().print("true");
            return;
        }
        response.getWriter().print(msg);
    }

    /**
     * 
     * @Title: delItem
     * @Description: TODO(异步 删除单据车 某单据子项)
     * @param
     * @return
     * @throws
     */
    public void delItem() {
        Order order = getorderSession(dealType);
        Set<OrderItem> Items = order.getOrderItems();
        for (OrderItem item : Items) {
            if (item.getGoods().getId().equals(goodsIdStr)) {
                Items.remove(item);
                break;
            }
        }
    }

    /**
     * 
     * @Title: Cleanorder
     * @Description: TODO(清空 一种单据明细车的session)
     * @param
     * @return
     * @throws
     */
    public void Cleanorder() {
        Cleanorder(dealType);
    }

    /**
     * 
     * @Title: Cleanorder
     * @Description: TODO(清空 一种单据明细车的session)
     * @param dealType
     *            操作类型
     * @return
     * @throws
     */
    private void Cleanorder(String dealType) {
        getSession().remove("order" + dealType.trim());
    }

    /**
     * 
     * @Title: Saveorder
     * @Description: TODO(保存session 里面的订单到数据库 并更新库存 或 已上架信息表)
     * @param
     * @return
     * @throws
     */
    public void Saveorder() throws Exception {
        Order order = null;
        if (dealType.equals("1")) {
            order = (Order) getSession().get("order1");
            storageService.UpGoodsNumbyOrderItems(order.getOrderItems(), false);
            onshelvesInfoService.UpGoodsNumbyOrderItems(order, true);
        } else if (dealType.equals("2")) {
            order = (Order) getSession().get("order2");
            storageService.UpGoodsNumbyOrderItems(order.getOrderItems(), true);
            onshelvesInfoService.UpGoodsNumbyOrderItems(order, false);

        } else if (dealType.equals("3")) {
            order = (Order) getSession().get("order3");
            storageService.UpGoodsNumbyOrderItems(order.getOrderItems(), true);
        } else if (dealType.equals("4")) {
            order = (Order) getSession().get("order4");
            storageService.UpGoodsNumbyOrderItems(order.getOrderItems(), false);
        }
        orderService.save(order);
        Cleanorder(dealType);
    }

    public String getStorageIdStr() {
        return storageIdStr;
    }

    public void setStorageIdStr(String storageIdStr) {
        this.storageIdStr = storageIdStr;
    }

    public String getMarketId() {
        return marketId;
    }

    public void setMarketId(String marketId) {
        this.marketId = marketId;
    }

    public String getDealType() {
        return dealType;
    }

    public void setDealType(String dealType) {
        this.dealType = dealType;
    }

    public String getGoodsIdStr() {
        return goodsIdStr;
    }

    public void setGoodsIdStr(String goodsIdStr) {
        this.goodsIdStr = goodsIdStr;
    }

    public String getGoodsName() {
        return GoodsName;
    }

    public void setGoodsName(String goodsName) {
        GoodsName = goodsName;
    }

    public String getSupplierId() {
        return supplierId;
    }

    public void setSupplierId(String supplierId) {
        this.supplierId = supplierId;
    }

    public String getGoodsCateId() {
        return goodsCateId;
    }

    public void setGoodsCateId(String goodsCateId) {
        this.goodsCateId = goodsCateId;
    }

    public String getGoodsnum() {
        return goodsnum;
    }

    public void setGoodsnum(String goodsnum) {
        this.goodsnum = goodsnum;
    }

}
